<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>文件上传</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      .custom-upload {
        position: relative;
        display: inline-block;
        overflow: hidden;
        margin: 10px;
      }

      .upload-input {
        position: absolute;
        left: 0;
        top: 0;
        opacity: 0;
        width: 100%;
        height: 100%;
        cursor: pointer;
      }

      .upload-button {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        padding: 6px 16px;
        font-size: 14px;
        font-weight: 400;
        line-height: 1.5;
        color: #fff;
        background-color: #1890ff;
        border: 1px solid #1890ff;
        border-radius: 2px;
        box-shadow: 0 2px 0 rgba(0, 0, 0, 0.045);
        cursor: pointer;
        transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
      }

      .upload-button:hover {
        background-color: #40a9ff;
        border-color: #40a9ff;
      }

      .upload-button:active {
        background-color: #096dd9;
        border-color: #096dd9;
      }

      .upload-button:focus {
        outline: 0;
        box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
      }

      .upload-icon {
        margin-right: 8px;
        font-size: 16px;
      }

      .el-input {
        width: calc(50vw - 40px);
        height: 50vh;
        display: block;
        padding: 10px 15px;
        font-size: 14px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        outline: none;
        transition: border-color 0.3s;
      }

      .el-input:focus {
        border-color: #409eff;
      }

      /* 按钮样式 */
      .el-button {
        padding: 10px 20px;
        font-size: 14px;
        color: white;
        background-color: #409eff;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        transition: background-color 0.3s;
      }

      .el-button:hover {
        background-color: #66b1ff;
      }

      .el-button:disabled {
        background-color: #c0c4cc;
        cursor: not-allowed;
      }

      /* 开关 */
      .switch {
        position: relative;
        display: block;
        width: 60px;
        height: 34px;
      }

      /* 隐藏默认的checkbox */
      .switch input {
        opacity: 0;
        width: 0;
        height: 0;
      }

      /* 滑块样式 */
      .slider {
        position: absolute;
        cursor: pointer;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #ccc;
        transition: 0.4s;
        border-radius: 34px;
      }

      /* 滑块圆形部分 */
      .slider:before {
        position: absolute;
        content: "";
        height: 26px;
        width: 26px;
        left: 4px;
        bottom: 4px;
        background-color: white;
        transition: 0.4s;
        border-radius: 50%;
      }

      .swtext {
        position: absolute;
        content: "";
        height: 26px;
        width: 260px;
        left: 70px;
      }

      /* 选中状态下的滑块背景 */
      input:checked + .slider {
        background-color: #2196f3;
      }

      /* 选中状态下滑块的位置 */
      input:checked + .slider:before {
        transform: translateX(26px);
      }

      /* 开关文字（可选） */
      .switch-label {
        margin-left: 10px;
        vertical-align: super;
      }
      .contentBox {
        display: flex;
      }
      .copyBox {
        position: relative;
        width: calc(50vw - 40px);
        height: 50vh;
        display: block;
        padding: 10px 15px;
        font-size: 14px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
      }
      .copy {
        width: 96px;
      }
      .box2 {
        position: relative;
        width: calc(50% - 40px);
        display: flex;
        flex-direction: column;
      }
    </style>
    <script src="./xlsx.full.min.js"></script>
    <script src="./axios.min.js"></script>
  </head>
  <body>
    <div class="custom-upload">
      <input type="file" id="upload" accept="image/*" class="upload-input" />
      <button type="button" class="upload-button">
        <span id="text">+ 上传图片</span>
      </button>
    </div>
    <label class="switch">
      <input type="checkbox" id="toggleSwitch" />
      <span class="slider slider"></span>
      <span class="swtext">是否自动下载表格</span>
    </label>
    <div class="contentBox">
      <div class="input-with-button">
        <!-- 输入框 -->
        <textarea
          type="text"
          class="el-input"
          id="inputValue"
          placeholder="请输入内容"
        >
        </textarea>
        <!-- 按钮 -->
        <button class="el-button" id="submitButton">开始识别</button>
        <button class="el-button" onclick="clearInput()">清空输入框</button>
      </div>

      <div class="box2">
        <div class="copyBox" id="copyBox"></div>
        <button class="el-button copy" id="copy" onclick="copy()">
          一键复制
        </button>
      </div>
    </div>

    <script>
      const input = document.getElementById("inputValue");
      const button = document.getElementById("submitButton");
      const copyBox = document.getElementById("copyBox");
      const copyText = copyBox.innerText;
      async function copy() {
        await navigator.clipboard.writeText(copyText);
        alert("复制成功！");
      }
      function clearInput() {
        input.value = ""; // 直接赋值为空字符串
      }
      button.addEventListener("click", async () => {
        if (!input.value) {
          alert("请输入内容");
        }
        copyBox.innerText = "";
        try {
          button.innerText = "正在识别中...";
          const response = await axios.post(
            "http://180.76.133.196:3000/postcontent",
            {
              value: input.value,
              checked: document.getElementById("toggleSwitch").checked,
            },
            {
              headers: {
                "Content-Type": "application/json", // 设置请求头
              },
            }
          );
          button.innerText = "开始识别";
          if (document.getElementById("toggleSwitch").checked) {
            alert(`识别成功，开始下载`);
            clearInput();
            const { success, orders } = response.data; // axios 自动解析 JSON，数据在 response.data
            console.log("data", response.data, orders);
            exportToExcel(orders);
          } else {
            const { success, value } = response.data; // axios 自动解析 JSON，数据在 response.data
            copyBox.innerText = value;
          }
        } catch (error) {
          console.error("请求失败:", error);
          alert("请求失败！查看控制台错误信息");
        }
      });

      document
        .getElementById("upload")
        .addEventListener("change", async function (e) {
          changeText("上传识别中...");
          const file = e.target.files[0];

          if (!file) return;
          if (!file.type.startsWith("image/")) {
            alert("请选择图片文件");
            return;
          }

          // 上传
          const formData = new FormData();
          formData.append("file", file);
          formData.append(
            "checked",
            document.getElementById("toggleSwitch").checked
          );
          copyBox.innerText = "";
          // 使用 axios 发送请求
          // http://180.76.133.196:3000/upload
          axios
            .post("http://180.76.133.196:3000/upload", formData, {
              headers: {
                "Content-Type": "multipart/form-data", // 确保正确设置 Content-Type
              },
              timeout: 116000000, // 60秒超时（单位：毫秒）
            })
            .then((response) => {
              changeText("+ 上传图片");
              if (document.getElementById("toggleSwitch").checked == true) {
                alert(`上传成功，开始下载`);
                console.log("response", response);
                const { success, orders } = response.data; // axios 自动解析 JSON，数据在 response.data
                console.log("data", response.data, orders);
                exportToExcel(orders);
              } else {
                const { success, value } = response.data; // axios 自动解析 JSON，数据在 response.data
                copyBox.innerText = value;
              }
            })
            .catch((error) => {
              console.error("上传失败:", error);
              if (error.response) {
                // 服务器返回了错误响应（如 4xx/5xx）
                alert(
                  `上传失败: ${error.response.data.message || error.message}`
                );
              } else {
                // 网络错误或请求未发出
                alert("上传失败: 网络错误或服务器无响应");
              }
            });
        });

      function changeText(val) {
        document.getElementById("text").innerText = val;
      }

      // 生成JSON
      function exportToExcel(jsonData) {
        const now = new Date();
        const formattedTime = `${now.getFullYear()}-${
          now.getMonth() + 1
        }-${now.getDate()} ${now.getHours()}:${String(
          now.getMinutes()
        ).padStart(2, "0")}`;
        console.log(formattedTime);
        // 1. 创建工作簿
        const wb = XLSX.utils.book_new();

        // 2. 将JSON转为工作表
        const ws = XLSX.utils.json_to_sheet(jsonData, {
          header: ["款号", "颜色", "尺码", "数量"], // 自定义表头
          skipHeader: false, // 包含表头
        });

        // 4. 将工作表添加到工作簿
        XLSX.utils.book_append_sheet(wb, ws, `订单数据${formattedTime}`);

        // 5. 生成文件并下载
        XLSX.writeFile(wb, `订单数据${formattedTime}.xlsx`);
        alert("下载成功");
      }
    </script>
  </body>
</html>
